﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace Enter.DataProxy.ProxyAdapter.Configuration
{
    public class DatabasesCollection : ConfigurationElementCollection
    {
        public static readonly string NodeName = "databases";
        private ConfigurationProperty _defaultProperty;

        protected override string ElementName
        {
            get
            {
                return DatabaseElement.NodeName;
            }
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }

        public DatabasesCollection()
        {
            _defaultProperty = new ConfigurationProperty("default", typeof(string), null, ConfigurationPropertyOptions.IsRequired);
            this.Properties.Add(_defaultProperty);
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new DatabaseElement();
        }

        /// <summary>
        /// 验证节点名称惟一性验证
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((DatabaseElement)element).Name;
        }

        /// <summary>
        /// 获取指定的数据库连接名称信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public new DatabaseElement this[string name]
        {
            get
            {
                foreach (var item in this)
                {
                    DatabaseElement database = item as DatabaseElement;
                    if (database != null && database.Name == name)
                        return database;
                }

                throw new AdapterException(string.Format("配置未包含名称为[{0}]的数据库。"));
            }
        }

        /// <summary>
        /// 获取默认的数据库
        /// </summary>
        public DatabaseElement DefaultDatabase
        {
            get
            {
                return (DatabaseElement)BaseGet(0);
                #warning DatabaseElement
                //var database = (DatabaseElement)BaseGet(BaseGet(_defaultProperty));
                //if (database != null)
                //    return database;
                //else
                //    throw new AdapterException("配置找不到默认数据库。");
            }
        }
    }
}
